import smtplib
import uuid
from email.header import Header
from email.mime.text import MIMEText
from importlib import reload

import redis as redis

from entity.common.constant.server import ServerConstant


# 操作连接池，暂时先放到这里
redisPool = redis.ConnectionPool(host=ServerConstant.SERVER_HOST, port=6379, decode_responses=True)
def sendEmail(targetEmail):
    print("发送邮箱的逻辑")
    code = str(uuid.uuid4()).replace('-', '')[1:5]
    print("code is :"+code)
    try:
        saveCodeToRedis(email=targetEmail,code=code)
        emailInfo = "欢迎注册软工电商系统，您的验证码是: <strong> "  + code  + " </strong>，有效时间为 5 分钟。 如果不是您本人操作请忽略该邮件"
        msg = MIMEText(emailInfo, 'html', 'utf-8')
        msg['From'] = "1983449241@qq.com"
        msg['To'] = targetEmail
        msg['Subject'] = Header("注册邮件", 'utf-8')
        # 使用smtplib模块发送邮件
        email_client = smtplib.SMTP("smtp.qq.com")
        # 失误将 授权码传到了 gitee，关闭了qq邮箱的 POP3服务，测试的时候开启
        email_client.login("1983449241@qq.com", "yucfpdbftaledced")
        email_client.sendmail("1983449241@qq.com", targetEmail, msg.as_string())
    except Exception as err:
        print(err)
        removeCodeFromRedis(email=targetEmail)
    finally:
        email_client.quit()

# 从 redis 中获得数据
def verfiyCode(email,code):
    redisCli = redis.Redis(connection_pool=redisPool,db=1)
    res=redisCli.get(email)
    return res==code

def saveCodeToRedis(email,code):
    redisCli = redis.Redis(connection_pool=redisPool,db=1)
    redisCli.setex(email,300,code)
    print("存入redis的 code 为: "+code)

def removeCodeFromRedis(email):
    redisCli = redis.Redis(connection_pool=redisPool,db=1)
    redisCli.delete(email)
